<?php
class PaycallbackControl extends Control{
	function __construct(){
		parent::__construct();
        $this->model=new Model();
        $this->time=time();
	}

	function agri_result(){
         
        $msg = base64_decode($_POST['MSG']);
        preg_match("/\<Message\>(.*)\<\/Message\>.*\<Signature\>(.*)\<\/Signature\>/i",$msg,$match);
        $contents = $match[1];
        $signature = $match[2];
         
        $pub_cert_file = UPATH . '/library/payments/agri/TrustPay.pem';
        $rs=$this->_verify($contents,$signature,$pub_cert_file );
        $xml = new Xml();
        $msg = $xml->xml2array($msg);
        $statu=$msg["MSG"]["Message"]["TrxResponse"]["ReturnCode"];
        $order_sn_main=$msg["MSG"]["Message"]["TrxResponse"]["OrderNo"];
        $money=$msg["MSG"]["Message"]["TrxResponse"]["Amount"];
        
        if($rs && ($statu=="0000")){
            $this->model->table="tcz_charge_order";
            $this->model->alias="co";
            $order=$this->model->get("serial_number='{$order_sn_main}'");
            if($order["status"]==1) $this->_cue("充值成功","充值成功，流水号为：{$order_sn_main}");
            $this->model->begin_transaction();
            if(!$this->set_order_status($order_sn_main,1)){$this->model->rollback_transaction();}
            if(!$this->pay_record($order_sn_main,$money,$order)){$this->model->rollback_transaction();}
            if(!$this->bhb_record($order_sn_main,$money,$order)){$this->model->rollback_transaction();}
            if(!$this->bhb_amount($money,$order)){$this->model->rollback_transaction();}
            if(!$this->update_paysign($order_sn_main)){$this->model->rollback_transaction();}
            $this->model->commit_transaction();
            $this->_cue("充值成功","充值成功，流水号为：{$order_sn_main}");
        	
        }        
        $this->_cue("充值失败","充值失败，流水号为：{$order_sn_main}");

    }
    function notify_alipay(){
        //$this->saveLog("开始验证","start");
        $retAVF = $this->_alipayVerify();
        //$this->saveLog("验证结束","{$retAVF}");
        if($retAVF == false){
            //验证失败
            exit('forbidden');
        }
        $this->model->table="tcz_charge_order";
        $this->model->alias="co";
        $order=$this->model->get("serial_number='{$this->order_sn_main}'");
        $money=$order["recharge_amount"];
        //if($order["status"]==1) $this->_cue("充值成功","充值成功，流水号为：{$order_sn_main}");
        //$this->saveLog("查询订单",var_export($order));
        $this->model->begin_transaction();
        if(!$this->set_order_status($this->order_sn_main,1)){$this->model->rollback_transaction();}
        if(!$this->pay_record($this->order_sn_main,$money,$order)){$this->model->rollback_transaction();}
        if(!$this->bhb_record($this->order_sn_main,$money,$order)){$this->model->rollback_transaction();}
        if(!$this->bhb_amount($money,$order)){$this->model->rollback_transaction();}
        if(!$this->update_paysign($this->order_sn_main)){$this->model->rollback_transaction();}
        $this->model->commit_transaction();
        $this->payment->verify_result(true);//告知支付宝成功信息
    }
    function return_alipay(){
        $retAVF = $this->_alipayVerify();
        //var_dump($retAVF);
        if($retAVF == false){
            //验证失败
            exit('forbidden');
        }
        $this->_cue("充值成功","充值成功，流水号为：{$this->order_sn_main}");
    }


    /* 淘宝返回校验 */
    private function _alipayVerify(){
        $notify              = $this->_get_notify();
        $this->out_order_sn  = $notify['out_trade_no'];
        $this->order_sn_main = $notify['main'];
       
        $retOSM             = $this->_checkOrderSnMain($notify['main']);
        $retOSM && $retSCT = $this->checkPayType('alipay');
        if($retOSM == false || $retSCT == false){
            return false;
        }
        
        /* 校验支付方式(根据上部的out_order_sn和order_sn_main) */
        
        $this->saveLog($this->order_sn_main,'支付状态：' . $notify['trade_status']);
        if(isset($notify['trade_status']) && $notify['trade_status'] <> 'TRADE_FINISHED' && $notify['trade_status'] <> 'TRADE_SUCCESS'){
            return false;
        }
        
        /* 调用相应的支付方式 */
        $this->payment = $this->_get_payment('alipay', $this->payInfo);
        /* 获取验证结果 */
       // $notify_result = $this->payment->verify_notify($notify, $this->paySign, true);
      
        $notify_result = $this->payment->verify_notify($notify, $this->paySign, true);  
        if($notify_result === false){
            /* 支付失败 */
            $this->saveLog($this->order_sn_main,json_encode($this->payment->get_error()));
            $this->payment->verify_result(false);
            return false;
        }
        return true;
    }

    /* 获取->检查主订单号 并返回 */
    private function _checkOrderSnMain($order_sn_main = ''){
        if(!$order_sn_main){
            $this->saveLog('','回调失败,主订单号丢失！');
            return false;
        }
        $this->allPayed = true;//本订单假定支付完成
        $info=modcall("charge_order","find",array(
            array(
                "condition"=>"serial_number='$order_sn_main'",
                "fields"=>"pay_type,status"
            )
        ));
        foreach($info as $sonInfo){
            $sonInfo['status'] != 1 && $this->allPayed = false;//未支付完成
        }
        
        if(empty($info)){
            $this->saveLog($order_sn_main,'主订单号在订单表中不存在数据！');
            return false;
        }
        $this->orderInfo = $info;
        $this->order_sn_main = $order_sn_main;
        return true;
    }

    /* 校验支付方式 并返回支付配置信息 */
    private function checkPayType($code){
        $paySign=modcall("paysign","get",array(
            array(
                'condition' => "out_order_sn = '{$this->out_order_sn}' AND order_sn_main = '{$this->order_sn_main}'"
            )
        ));
        $payInfo=modcall("payment","get",array(
            array(
                'condition' => "payment_code = '{$code}'"
            )
        ));
        if(empty($paySign) || empty($payInfo) || $paySign['pay_id'] != $payInfo['payment_id']){
            $this->saveLog($this->order_sn_main,"支付方式校验不正确,可能存在以下情况:1,支付记录为空;2,{$code}支付方式不存在;3,前两者记录的支付方式ID不相等！外部交易号：{$this->out_order_sn}");
            return false;
        }
        $this->paySign = $paySign;
        $this->payInfo = $payInfo;
        return true;
    }

    /* 取得支付方式实例 */

    function _get_payment($code, $payment_info) {
        include_once(UPATH . '/library/payments/payment.base.php');
        include(UPATH . '/library/payments/alipay/alipay.payment.php');
        $class_name = ucfirst($code) . 'Payment';
        return new $class_name($payment_info);
    }

    private function saveLog($str1,$str2) 
    {
        cdlog("{$str1}---{$str2}","",true);
    }

    private function _get_notify(){
        return array_merge($_GET,$_POST);
    }


    function _verify($data,$signature,$cert_file){
        $fp = fopen($cert_file, "r");
        $cert = fread($fp, 8192);
        fclose($fp);
        $pubkeyid = openssl_get_publickey($cert);
        $signature = base64_decode($signature);
        // state whether signature is okay or not
        $ok = openssl_verify($data, $signature, $pubkeyid);
        openssl_free_key($pubkeyid);
        return $ok;
    }


    //支付成功，更改订单状态，插入一条充值记录，设置余额
    function set_order_status($order_sn,$status){
        $this->model->table="tcz_charge_order";
        $this->model->alias="co";
        return $this->model->edit("serial_number='{$order_sn}'",array(
            "status"=>1,
            "pay_time"=>$this->time
        ));
    }

    //插入一条支付记录
    function pay_record($order_sn,$money,$order){
        $this->model->table="tcz_order_pay";
        $this->model->alias="op";
        return $this->model->add(array(
            "order_id"=>$order["order_id"],
            "order_sn_main"=>"{$order_sn}",
            "payment_id"=>$order['pay_type'],
            "money"=>$money,
            "pay_time"=>$this->time,
            "status"=>"succ"

        ));
    }

    //插入博货宝增长记录
    function bhb_record($order_sn,$money,$order){
        $this->model->table="tcz_member_vcount";
        $this->model->alias="mv";
        return $this->model->add(array(
            "user_id"=>$order["user_id"],
            "order_id"=>$order['order_id'],
            "order_sn_main"=>"{$order_sn}",
            "countvalue"=>$money,
            "source"=>3,
            "add_time"=>date("Y-m-d H:i:s",$this->time),
            "operate_id"=>0,
            "note"=>"博货宝充值"
        ));
    }

    //设置博货宝账户余额
    function bhb_amount($money,$order){
        $this->model->table="tcz_member";
        $this->model->alias="m";
        return $this->model->edit("user_id={$order['user_id']}",array(
            "vcount"=>"vcount+{$money}"
        ));
    }

    //更改支付记录状态
    function update_paysign($order_sn){
        $this->model->table="tcz_order_paysign";
        $this->model->alias="op";
        return $this->model->edit("order_sn_main='{$order_sn}'",array(
            "status"=>"succ",
            "ftime"=>$this->time
        ));
    }
}
?>